﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using MediaPortal.Configuration;

namespace BierdopjeTV.API
{
    class APIFunctions
    {

        //private string url = @"http://www.djredmar.com/api/";
        //private string fanart_url = @"http://cdn.bierdopje.eu/uploads/images/shows/billboard/";
        private string fanart_url = @"http://www.djredmar.com/bierdopje/uploads/images/shows/billboard/";
        private string url = @"http://api.bierdopje.com/";
        private string API_KEY = @"B390F0D22A277283";

        
        public List<BierdopjeShows> FindShowByName(string Showname)
        {
            string _url;

            //calculate url
            _url = url + API_KEY + "/FindShowByName/" + Showname.Replace(" ", "_");

            XmlDocument _XML = Helpers.XMLHelper.getXML(_url);
            XmlDocument subXML = new XmlDocument();

            List<BierdopjeShows> _BierdopjeShows = new List<BierdopjeShows>();
            BierdopjeShows _Show;

            string innerXML;
            string XPathQuery ;
            
            //bug in api
            if (_XML.SelectNodes("/bierdopje/response/cached").Count > 0)
            {
                XPathQuery = "/bierdopje/response/results/result";                
            }
            else
            {
                XPathQuery = "/bierdopje/response/results/genre";
            }


            int Nodes = _XML.SelectNodes(XPathQuery).Count;

            for (int i = 0; i < Nodes; i++)
            {
                innerXML = "<result>" + _XML.SelectNodes(XPathQuery)[i].InnerXml.ToString() + "</result>";                
                subXML.LoadXml(innerXML);

                _Show = new BierdopjeShows();
                try {
                    _Show.ShowID = Convert.ToInt32(subXML.SelectSingleNode("/result/showid").InnerText);
                    _Show.ShowName = subXML.SelectSingleNode("/result/showname").InnerText;
                    _Show.Seasons = Convert.ToInt32(subXML.SelectSingleNode("/result/seasons").InnerText);
                    _Show.Episodes = Convert.ToInt32(subXML.SelectSingleNode("/result/episodes").InnerText);
                    _Show.ShowStatus = subXML.SelectSingleNode("/result/showstatus").InnerText;
                    _Show.AirTime = subXML.SelectSingleNode("/result/airtime").InnerText;
                    _Show.Summary = subXML.SelectSingleNode("/result/summary").InnerText;
                    _Show.FirstAired = subXML.SelectSingleNode("/result/firstaired").InnerText;
                    _Show.TVDBID = Convert.ToInt32(subXML.SelectSingleNode("/result/tvdbid").InnerText);
                    _Show.LastAired = subXML.SelectSingleNode("/result/lastaired").InnerText;
                    _Show.NextEpisode = subXML.SelectSingleNode("/result/nextepisode").InnerText;
                    _Show.Runtime = Convert.ToInt32(subXML.SelectSingleNode("/result/runtime").InnerText);
                    _Show.Score = Convert.ToDouble(subXML.SelectSingleNode("/result/score").InnerText);
                    _Show.Favorites = Convert.ToInt32(subXML.SelectSingleNode("/result/favorites").InnerText);                    
                    _Show.HasTranslators = subXML.SelectSingleNode("/result/has_translators").InnerText;

                    //NETWORK IS NOT YET SUPPORTED!!!!!!!!!!!!
                    _Show.Network = "NOTSUPPORTED YET";

                }
                catch (Exception)   {}
                                
                _BierdopjeShows.Add(_Show); //add object to collection.

            }
          
            return _BierdopjeShows;
        }

        public BierdopjeShows GetShowById(int ShowID)
        {
            string _url;

            //calculate url
            _url = url + API_KEY + "/GetShowById/" + ShowID.ToString();

            XmlDocument _XML = Helpers.XMLHelper.getXML(_url);
                        
            BierdopjeShows _Show;

            
            _Show = new BierdopjeShows();
            try
            {
                _Show.ShowID = Convert.ToInt32(_XML.SelectSingleNode("/bierdopje/response/showid").InnerText);
                _Show.ShowName = _XML.SelectSingleNode("/bierdopje/response/showname").InnerText;
                _Show.Seasons = Convert.ToInt32(_XML.SelectSingleNode("/bierdopje/response/seasons").InnerText);
                _Show.Episodes = Convert.ToInt32(_XML.SelectSingleNode("/bierdopje/response/episodes").InnerText);
                _Show.ShowStatus = _XML.SelectSingleNode("/bierdopje/response/showstatus").InnerText;
                _Show.AirTime = _XML.SelectSingleNode("/bierdopje/response/airtime").InnerText;
                _Show.Summary = _XML.SelectSingleNode("/bierdopje/response/summary").InnerText;
                _Show.FirstAired = _XML.SelectSingleNode("/bierdopje/response/firstaired").InnerText;
                _Show.TVDBID = Convert.ToInt32(_XML.SelectSingleNode("/bierdopje/response/tvdbid").InnerText);
                _Show.LastAired = _XML.SelectSingleNode("/bierdopje/response/lastaired").InnerText;
                _Show.NextEpisode = _XML.SelectSingleNode("/bierdopje/response/nextepisode").InnerText;
                _Show.Runtime = Convert.ToInt32(_XML.SelectSingleNode("/bierdopje/response/runtime").InnerText);
                _Show.Score = Convert.ToDouble(_XML.SelectSingleNode("/bierdopje/response/score").InnerText);
                _Show.Favorites = Convert.ToInt32(_XML.SelectSingleNode("/bierdopje/response/favorites").InnerText);                    
                _Show.HasTranslators = _XML.SelectSingleNode("/bierdopje/response/has_translators").InnerText;

                //NETWORK IS NOT YET SUPPORTED!!!!!!!!!!!!
                _Show.Network = "NOTSUPPORTED YET";

            }
            catch (Exception) { }
                       

            return _Show;
        }

        public List<BierdopjeEpisodes> GetEpisodesForSeason(int ShowId, int Season)
        {
            List<BierdopjeEpisodes> _BierdopjeEpisodes = new List<BierdopjeEpisodes>();
            BierdopjeEpisodes _Episode;
           
            //The bierdopje api
            string _url;

            //calculate url
            _url = url + API_KEY + "/GetEpisodesForSeason/" + ShowId.ToString() + "/" + Season.ToString();            

            XmlDocument _XML = Helpers.XMLHelper.getXML(_url);
            XmlDocument subXML = new XmlDocument();
            
            string innerXML;
            string XPathQuery ;
            
            //bug in api
            XPathQuery = "/bierdopje/response/results/result";

            int Nodes = _XML.SelectNodes(XPathQuery).Count;
            for (int i = 0; i < Nodes; i++)
            {
                innerXML = "<result>" + _XML.SelectNodes(XPathQuery)[i].InnerXml.ToString() + "</result>";                
                subXML.LoadXml(innerXML);

                _Episode = new BierdopjeEpisodes();
                try {
                    _Episode.ShowID = ShowId; //doh :-)
                    _Episode.EpisodeID = Convert.ToInt32(subXML.SelectSingleNode("/result/episodeid").InnerText);
                    _Episode.TVDBID = Convert.ToInt32(subXML.SelectSingleNode("/result/tvdbid").InnerText);
                    _Episode.Score = Convert.ToDouble(subXML.SelectSingleNode("/result/score").InnerText);
                    _Episode.Votes = Convert.ToInt32(subXML.SelectSingleNode("/result/votes").InnerText);
                    _Episode.SubsEN = subXML.SelectSingleNode("/result/subsnl").InnerText;
                    _Episode.SubsNL = subXML.SelectSingleNode("/result/subsen").InnerText;
                    _Episode.Titel = subXML.SelectSingleNode("/result/title").InnerText;
                    _Episode.Season = Convert.ToInt32(subXML.SelectSingleNode("/result/season").InnerText);
                    _Episode.Episode = Convert.ToInt32(subXML.SelectSingleNode("/result/episode").InnerText);
                    _Episode.AirDate = subXML.SelectSingleNode("/result/airdate").InnerText;
                    _Episode.Summary = subXML.SelectSingleNode("/result/summary").InnerText;
                    


                }
                catch (Exception)   {}

                _BierdopjeEpisodes.Add(_Episode); //add object to collection.

                _Episode = null;
            }
          
            return _BierdopjeEpisodes;
        }

        public void DownloadBillBoard(int ShowID)
        {            

            string bb_url;

            string localfile = Config.GetFolder(Config.Dir.Thumbs) + @"\BierdopjeTV\" + ShowID.ToString() + ".jpg";

            if (ShowID == 0)
            {
                //If showid = 0; we want the placeholder :-)
                bb_url = fanart_url + "placeholder_bb";
                
            }
            else
            {
                bb_url = fanart_url + ShowID.ToString();
                
            }

            //try to get jpg
            if (!Helpers.HTTPHelper.DownloadFile(bb_url + ".jpg", localfile))
            {
                System.Diagnostics.Debug.Print("\t\t JPG Niet gevonden!");
                //try to get png                
                if (!Helpers.HTTPHelper.DownloadFile(bb_url + ".png", localfile))
                {
                    System.Diagnostics.Debug.Print("\t\t PNG Niet gevonden!");
                    //try to get jpeg                    
                    if (!Helpers.HTTPHelper.DownloadFile(bb_url + ".jpeg", localfile))
                    {
                        System.Diagnostics.Debug.Print("\t\t JPEG Niet gevonden!");
                    }

                }
            }
        }

    }

}
